package com.dhecp.project.api.controller;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.project.api.domain.ApiResponse;
import com.dhecp.project.api.service.Api1688Service;
import com.dhecp.project.api.service.ApiLogService;
import com.dhecp.project.api.util.ApiConfig;

/**
 * @ClassName Api1688Controller
 * @Description
 * @Author alula
 * @Date 2022-08-25 20:12
 */
@Controller
@RequestMapping("/api/1688")
public class Api1688Controller {

    private static final Logger logger = LoggerFactory.getLogger(Api1688Controller.class);

    //1688系统名称
    private static final String OPEN1688_SYSTEM_NAME = "1688";
	
	private BlockingQueue<Long> queue = new LinkedBlockingQueue<Long>(100);

    @Autowired
    private Api1688Service api1688Service;

    @Autowired
    private ApiLogService apiLogService;

    /**
     * 1688授权回调
     * @param code
     */
    @RequestMapping("/authcallback")
    public void authCallBack(@RequestParam(required = true) String code, HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(code)){
            logger.error("获取1688授权回调时code值为空！");
        }else {
            ApiResponse apiResponse = api1688Service.get1688Token(code);
            if (apiResponse.getSuccess() == true){
                response.sendRedirect(ApiConfig.getApiDeployUrl()+"/api/1688/tokenauth?auth=yes");
            }else {
                response.sendRedirect(ApiConfig.getApiDeployUrl()+"/api/1688/tokenauth?auth=no");
            }
        }
    }

    /**
     * 获取token回调地址
     * @return
     */
    @RequestMapping("/tokenauth")
    public  String tokenCallBack(@RequestParam(required = true) String auth, ModelMap mmap){
        if (StringUtils.isEmpty(auth)){
            auth = "no";
        }
        String message = "";
        if (auth.contains("yes")){
            message = "授权成功!";
        }else{
            message = "授权失败!";
        }
        mmap.put("message", message);
        return "error/tokenauth";
    }

    /**
     * 刷新token
     * @return
     */
    @RequestMapping("/refreshtoken")
    @ResponseBody
    public  AjaxResult refreshToken(){
        String token = api1688Service.getRefreshAccessToken();
        return AjaxResult.success(token);
    }

    /**
     * 接收1688消息
     */
    @RequestMapping("/pushMessage")
    @ResponseBody
    public String pushMessage(@RequestParam(required = true) Map<String, Object> params, HttpServletResponse response){
        ApiResponse apiResponse = new ApiResponse();
        String type = "Push1688Message";
        try {
			if (queue.offer(System.currentTimeMillis(), 2, TimeUnit.SECONDS)) {
		    	queue.poll(0, TimeUnit.SECONDS);
	            apiResponse = api1688Service.push1688Message(OPEN1688_SYSTEM_NAME, type, params);
			}
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API处理1688回调消息出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
            if (apiResponse.getSuccess() == true){
                response.setStatus(200);
                return  "200";
            }else {
                response.setStatus(500);
                return  "500";
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API处理1688回调消息出错，错误为" + ex.getMessage());
            response.setStatus(500);
            return  "500";
        }
    }

    /**
     * 根据产品ID获取1688产品信息
     * @param params 格式为{"productNos":"EE921102901,EE921102902","userId":"0000","pCode":"母件编码","pName":"母件名称"}
     * @return
     */
    @RequestMapping("/get1688ProductDetail")
    @ResponseBody
    public ApiResponse get1688ProductDetail(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Get1688ProductList";
        try {
        	apiResponse = api1688Service.get1688ProductDetail(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API调用1688根据商品ID列表获取商品接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API调用1688根据商品ID列表获取商品接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

     /**
     * 创建1688采购订单
     * @param params 格式为{"orderNos":"采购订单号PO-220831-000001,PO-220831-000002","userId":"0000"}
     * @return
     */
    @RequestMapping("/create1688Order")
    @ResponseBody
    public ApiResponse create1688Order(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Create1688Order";
        try {
        	apiResponse = api1688Service.create1688Order(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
                apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "ECP_API调用创建1688采购订单接口出错，错误为："+apiResponse.getMessage(), "", 0, "");
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用创建1688采购订单接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 取消1688采购订单
     * @param params  格式为{"orderNo":"采购订单号","userId":"0000","cancelReason":""}
     * @return
     */
    @RequestMapping("/cancel1688Order")
    @ResponseBody
    public ApiResponse cancel1688Order(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Cancel1688Order";
        try {
            apiResponse = api1688Service.cancel1688Order(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API调用取消1688采购订单接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用取消1688采购订单接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取1688订单详情信息
     * @param params 格式为{"orderNos":"采购订单号，多个用逗号隔开","userId":"0000"}
     * @return
     */
    @RequestMapping("/get1688OrderDetail")
    @ResponseBody
    public ApiResponse get1688OrderDetail(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Get1688OrderDetail";
        try {
            apiResponse = api1688Service.get1688OrderDetail(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API调用获取1688订单详情接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用获取1688订单详情接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取1688订单物流信息
     * @param params 格式为{"orderNo":"采购订单号","userId":"0000"}
     * @return
     */
    @RequestMapping("/get1688OrderLogisticsInfo")
    @ResponseBody
    public ApiResponse get1688OrderLogisticsInfo(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Get1688OrderLogisticsInfo";
        try {
            apiResponse = api1688Service.get1688OrderLogisticsInfo(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API调用获取1688订单物流信息接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用获取1688订单物流信息接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取1688订单物流跟踪信息
     * @param params 格式为{"orderNo":"采购订单号","userId":"0000"}
     * @return
     */
    @RequestMapping("/get1688OrderTraceInfo")
    @ResponseBody
    public ApiResponse get1688OrderTraceInfo(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Get1688OrderTraceInfo";
        try {
            apiResponse = api1688Service.get1688OrderTraceInfo(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_API调用获取1688订单物流跟踪信息接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用获取1688订单物流跟踪信息接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }

    /**
     * 获取1688订单支付URL地址
     * @param params 格式为{"aliOrderNos":"1688订单号多个用逗号分开","userId":"0000"}
     * @return
     */
    @RequestMapping("/get1688AlipayUrl")
    @ResponseBody
    public ApiResponse get1688AlipayUrl(@RequestParam(required = true) Map<String, Object> params)
    {
        ApiResponse apiResponse = new ApiResponse();
        String type = "Get1688OrderAlipayUrl";
        try {
            apiResponse = api1688Service.get1688AlipayUrl(OPEN1688_SYSTEM_NAME, type, params);
            if (apiResponse.getCode() == 500){
            	apiLogService.addApiLog(OPEN1688_SYSTEM_NAME, type, "dataParams：" + params, "ECP_APIru接口调用获取1688支付URL接口出错，错误为："+apiResponse.getMessage(), apiResponse.getCode(), apiResponse.getMessage());
            }
        }
        catch (Exception ex) {
            apiResponse.setCode(500);
            apiResponse.setMessage("ECP_API接口调用获取1688支付URL接口出错，错误为" + ex.getMessage());
        }
        return apiResponse;
    }
}
